﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinanceGoldPointDal.DTO;
using HtmlAgilityPack;
using FinanceGoldPointDal.DTO.Trans;
using MaasOne.Finance.YahooFinance;

namespace FinanceGoldPointDal.Utils
{
  public class GetterSymbolStatsBase : BaseStockUtil
  {
    QuoteUtilsYHOO _yhooQuoteUtils = new QuoteUtilsYHOO();


    public void aggiornaStatisticheSimbooliDB()
    {

   

      var simboli = GetSimboliBase(new DTO.Filters.QuoteFilter() { Location = "MIL"  });

      StatsQuote quote = null;
      RetData<StatsQuote> result = null; ;

      using (var dal = getNewDAL())
      {

        dal.ExecuteStoreCommand("truncate table statsimboli");


        foreach (var simb in simboli)
        {
          result = getStatBaseSimbolo(simb.Code);

          if (!result.HasErrors)
          {
            dal.AddToStatSimboli(result.Dati.FromDTOtoEntity());
            dal.SaveChanges();
          }
        }
      }

    }//fM
    
    

    public RetData<StatsQuote> getStatBaseSimbolo(string pCode)
    {
      if (string.IsNullOrEmpty(pCode)) return null ;

      var queryUrl = _yhooQuoteUtils.getYHQueryStatBase(pCode);

      var result = DownloadWebString(queryUrl);
      if (result.HasErrors)
      {
        return new RetData<StatsQuote>(new Exception("Dati non prelevati"));
      }

      var dom = getDomDocument(result.Dati);
      bool ok = false;

      StatsQuote stat = new StatsQuote(pCode);


      ok = trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
            "Chiusura anno fiscale:", stat, (obj, dat) => { obj.ChiusuraAnnoFiscale = dat; });

      if (!ok) return new RetData<StatsQuote>(new Exception("Dati non trovati"));

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
            "Margine di profitto (ttm):", stat, (obj, dat) => { obj.MargineDiProfittoPerc = getDoubleNullValFromPercentual(TroncaNUltimiCaratteri(dat, 1)); });

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
            "Margine operativo (ttm):", stat, (obj, dat) => { obj.MargineOperativoPerc = getDoubleNullValFromPercentual(TroncaNUltimiCaratteri(dat, 1)); });

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Rendimento delle attivit", stat, (obj, dat) =>
          {
            obj.RendimentoAttivitaPerc =
              getDoubleNullValFromPercentual(TroncaNUltimiCaratteri(dat, 1));
          });

       trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "EBITDA (ttm)", stat, (obj, dat) =>
          {
            obj.EBITDA = getDoubleNullValFromGB(bonificaCifraDaDefMigliaia(dat));
          });

      

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Rendimento dei mezzi propri (ROE) (ttm):", stat, (obj, dat) => { obj.RendimentoMezziPropriPerc = 
            getDoubleNullValFromPercentual(TroncaNUltimiCaratteri(dat, 1)); });

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Ricavi (ttm):", stat, (obj, dat) => { obj.Ricavi = getDoubleNullValFromGB(bonificaCifraDaDefMigliaia(dat)); });

      trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Crescita dei ricavi trimestrali (yoy):", stat, (obj, dat) => { obj.CrescitaRicaviTrimPerc = getDoubleNullValFromPercentual(TroncaNUltimiCaratteri(dat, 1)); });

         trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Vol medi (3 mese)", stat, (obj, dat) => { obj.VolMedi3Mesi = getDoubleNullValFromGB(dat); });

       trovaInTDPrimaESettaValoreTDDopo<StatsQuote>(dom.DocumentNode,
          "Vol medi (10 giorno)", stat, (obj, dat) => { obj.VolMedi10GG = getDoubleNullValFromGB(dat); });
           

       return new RetData<StatsQuote>(stat);

    }


    public bool trovaInTDPrimaESettaValoreTDDopo<T>(HtmlNode pTrNode, string pTextToSearchInFirstTD, T pobj, Action<T,string> pFunc ) 
    {
      
      var nodi = getTDsInTablesDom(pTrNode, null, null, pTextToSearchInFirstTD);
       if (nodi != null & nodi.Count == 1)
       {
          pFunc.Invoke(pobj, nodi.FirstOrDefault().NextSibling.InnerText );
          return true;
       }
       return false;
    }


    //MAASONE
    public void prova()
    {
      var res = new MaasOne.Finance.YahooFinance.CompanyProfileDownload().Download(new CompanyProfileDownloadSettings("A2A.mi"));

      var res1 = new MaasOne.Finance.YahooFinance.CompanyStatisticsDownload().Download("A2A.mi");
      var res12 = new MaasOne.Finance.YahooFinance.QuotesDownload().Download("A2A.mi",
        new[] { QuoteProperty.Symbol, QuoteProperty.Open, QuoteProperty.DaysHigh });

      var rr = new MaasOne.Finance.YahooFinance.QuoteOptionsDownload().Download();

      var tt = new MaasOne.Finance.YahooFinance.MarketQuotesDownload().Download();

      var res2 = new MaasOne.Finance.YahooFinance.HistQuotesDownload().Download("A2A.mi",DateTime.Now.AddDays(-10),DateTime.Now, HistQuotesInterval.Daily);

      var res3 = new MaasOne.Finance.YahooFinance.MarketQuotesDownload().DownloadAllSectorQuotes();

      var res4 = new MaasOne.Finance.YahooFinance.MarketDownload().Download();

    }


  }
}
